# -*- coding: utf-8 -*-
# @time: 2024/5/15 17:19
# @file: IV_RV_data
# @author: tyshixi08

import time
from datetime import datetime
import pandas as pd
import rqdatac
from dateutil.relativedelta import relativedelta
from rqdatac import *
import numpy as np
import math
import warnings
import os
import matplotlib
import  matplotlib.pyplot as plt

warnings.filterwarnings('ignore')

# 米筐初始化
rqdatac.init('license', 'AcBHy5_JJ6wjZdu7Q-ey7dX-J3BmyEC_KblY2Q_hBeOuoBaeBbgXTNSe6XZvqKVESbyUf7vMpLLGuO_aqyb3w9fWGI7q4wdClE6cMp_Z3N4PqqTHJ0nr3CIuXtk-5XzSD1p7NTdNcrAfZlRVpMMtY_PDC9FYuXNmC_EnuQg4H-A=fGk9EhHcK3xN189iXYSWLyiMdGUeXXlVZqr2MxhBypSHxQYnIIyxyM8BR8oNnVUdWhKx-ZrFRIjSONd7uYpOvpcBab92P60iAR_JopX61emtrvsY1xG_uCfYhDPBdDSJKaniJhTPuoBIU4JZun8-8fMIxzx7lnwBm2kAUOA_Mpg=')

# 获取月份列表
def month_ls():
    start_date = datetime(2017, 1, 1)
    month_list = []
    while start_date != datetime(2030, 1, 1):
        month_str = start_date.strftime('%Y-%m')
        month_list.append(month_str)
        start_date += relativedelta(months=1)
    return month_list

# 获取对应时间段所有可转债代码及对应正股代码的字典
def get_all_convertible_code():
    df_all = pd.DataFrame()
    month_list = month_ls()
    for month in month_list:
        df = pd.DataFrame(convertible.all_instruments(f'{month}'))[['order_book_id', 'stock_code']]
        df_all = pd.concat([df_all, df])
    df_all = df_all.drop_duplicates()
    return df_all

# 获取所有可转债代码
def code_ls():
    ls = list(get_all_convertible_code()['order_book_id'])
    return ls

def stock_ls():
    ls = list(get_all_convertible_code()['stock_code'])
    return ls

# 获取基准指数表现
def basic_index():
    df = get_price('866005.RI', start_date=month_ls()[0] + '-01', end_date=month_ls()[-1] + '-01', frequency='1d', fields=['close', 'prev_close'])
    df['指数净值'] = df['close'] / df['close'].iloc[0]
    df = df.reset_index('date').rename(columns={'date':'交易日期'})[['交易日期', '指数净值']]
    df['交易日期'] = pd.to_datetime(df['交易日期']).dt.strftime('%Y-%m-%d %h:%m:%s')
    return df

# 保存到Excel
def save_Excel(df, name):
    wb = pd.ExcelWriter(f'{name}.xlsx')
    df.to_excel(wb, index=False)
    wb.close()

# 保存到CSV
def save_CSV(df, name):
    df.to_csv(f'{name}.csv', encoding='utf-8-sig', index=False)

